package com.qingfeng.core.config.database;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @description: 改变当前线程中的数据源
 * @author:LWY
 * @date: 2017/10/12 16:10
 * @modified:
 */
@Aspect
@Component
public class ReadOnlyConnectionInterceptor implements Ordered {

    public static final Logger LOGGER = LoggerFactory.getLogger(ReadOnlyConnectionInterceptor.class);

    /**
     * 环绕切入 在有 “@readOnlyConnection”注解的方法上
     *
     * @param proceedingJoinPoint 代理类
     * @param readOnlyConnection
     * @return
     * @throws Throwable
     */
    @Around("@annotation(readOnlyConnection)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, ReadOnlyConnection readOnlyConnection) throws Throwable {
        try {
            LOGGER.info("set database connection to read only");
            //更改数据库源为slave
            DataBaseContextHolder.setDataBaseType(DataBaseContextHolder.DataBaseType.SLAVE);
            Object result = proceedingJoinPoint.proceed();
            return result;
        } finally {
            //清空数据库源
            DataBaseContextHolder.clearDataBaseType();
            LOGGER.info("restore database connection");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

}